<template>
  <div>
    <div class="association-form">
      <div class="title">{{ formName }}</div>
      <div class="content">
        <span v-show="formList.length === 0">请选择{{ formName }}表单</span>
        <fks-button
          style="float: right; margin-right: 10px"
          icon="fks-icon-link"
          v-if="field.length > 0 && type && !isDisabled"
          @click="showForms"
          >关联表单</fks-button
        >
      </div>
    </div>
    <fks-dialog title="表单列表" :visible.sync="formListVisible">
      <ul class="dialog-content">
        <li class="form" v-for="(formItem, index) in formDetail" :key="index">
          <fks-radio
            style="width: 100%"
            v-model="checkedForm"
            :label="formItem.id"
            >{{ formItem.serial_number }}</fks-radio
          >
        </li>
      </ul>
      <span slot="footer" class="dialog-footer">
        <!-- <fks-button @click="formListVisible = false">取 消</fks-button> -->
        <fks-button type="primary" icon="fks-icon-check" @click="saveForm()">{{
          LANG.DETERMINE
        }}</fks-button>
      </span>
    </fks-dialog>
    <ul class="checked-form-content" v-if="detailVisible">
      <li class="form">
        <div class="form-content">
          <!-- <div class="time">表单编号：</div> -->
          <div class="title">编号：{{ dataValues.serial_number }}</div>
        </div>
        <div class="form-detail">
          <fks-form :model="dataValues" ref="ruleForm" label-width="100px">
            <fks-form-item
              style="margin-bottom: 10px"
              v-for="(item, index) in formData"
              :key="index"
              :label="item.name"
            >
              <fks-rate
                disabled
                v-if="item.tagAttribute === 'rate'"
                v-model="dataValues[item.id]"
              ></fks-rate>
              <fks-time-picker
                readonly
                is-range
                value-format="HH:mm:ss"
                v-else-if="item.tagAttribute === 'time-range'"
                v-model="dataValues[item.id]"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
              >
              </fks-time-picker>
              <fks-date-picker
                readonly
                v-else-if="item.tagAttribute === 'date-range'"
                v-model="dataValues[item.id]"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </fks-date-picker>
              <fks-slider
                v-else-if="item.tagAttribute === 'slider'"
                v-model="dataValues[item.id]"
                disabled
              ></fks-slider>
              <fks-switch
                v-else-if="item.tagAttribute === 'switch2'"
                v-model="dataValues[item.id]"
                disabled
              ></fks-switch>
              <form-upload
                v-else-if="item.tagAttribute === 'upload'"
                v-model="dataValues[item.id]"
                disabled
              ></form-upload>
              <write-Info
                class="information"
                :visible.sync="visible"
                v-else-if="item.tagAttribute === 'information'"
                :form="dataValues[item.id]"
              >
              </write-Info>

              <fks-input
                v-else
                v-model="dataValues[item.id]"
                readonly
              ></fks-input>
            </fks-form-item>
          </fks-form>
        </div>
      </li>
    </ul>
  </div>
</template>
<script>
import FormUpload from '@/modules/FormCenter/components/FormUpload/index.vue'
import writeInfo from '@/modules/FormCenter/componentsWp/writeInfo'
import DetailTable from '@/modules/FormCenter/componentsWp/detailTable'
import { getForms } from './api.js'

import { initialCustomForm } from '@/modules/FormCenter/api'
export default {
  name: 'AssociationForm',
  components: {
    FormUpload,
    writeInfo,
    DetailTable
  },
  props: {
    permission: {
      type: String,
      default: 'readonly'
    },
    formKey: {
      type: Array,
      default: () => {
        return []
      }
    },
    formName: {
      type: String,
      default: 'name'
    },
    field: {
      type: Array,
      default: () => {
        return []
      }
    },
    formList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      visible: true,
      formListVisible: false,
      dataValues: {},
      formDetail: [],
      checkedForm: '',
      uploadArr: [],
      detailVisible: false,
      type: !!this.$route.params.type
    }
  },

  computed: {
    isDisabled() {
      return this.permission == 'readonly' || this.type === 'view'
    },
    formData() {
      this.uploadArr = []
      let arr = this.field.map((item) => {
        if (item.tagAttribute === 'upload') {
          this.uploadArr.push(item.id.split('_')[0])
        }
        return item
      })
      return arr
    }
  },
  created() {
    if (this.formList[0] && this.formList[0].id) {
      this.checkedForm = this.formList[0].id
      this.detailVisible = !!this.checkedForm
      this.getValue()
    }
  },
  methods: {
    //formKey-获取全部的表单 formDetail
    showForms() {
      this.detailVisible = false
      this.formListVisible = true
      getForms(this.formKey[1]).then((res) => {
        if (res.status && res.data) {
          this.formDetail = res.data
        }
      })
    },
    getValue() {
      // 获取值的
      let returnData = {}
      let data = {
        formKey: this.formKey[1],
        id: this.checkedForm
      }
      return initialCustomForm(data)
        .then((res) => {
          if (res.status) {
            returnData = JSON.parse(JSON.stringify(res.data))
            // //删除基本字段
            const deleteArray = [
              'create_by',
              // 'create_date',
              'delete_flag',
              // 'id',
              'update_by',
              'update_date'
            ]
            deleteArray.forEach((item) => {
              this.$delete(returnData, item)
            })

            // field768: 值
            // 处理数组
            this.formData.forEach((item) => {
              let val = returnData[item.id.split('_')[0]]

              if (
                item.tagAttribute === 'time-range' ||
                item.tagAttribute === 'date-range'
              ) {
                let transValue = val.split(',')
                returnData[item.id.split('_')[0]] = JSON.parse(transValue)
              } else if (
                item.tagAttribute === 'notify' ||
                item.tagAttribute === 'cascader' ||
                item.tagAttribute === 'check-box'
              ) {
                let valArr = val ? JSON.parse(val) : []
                returnData[item.id.split('_')[0]] = valArr.join(',')
              } else if (
                item.tagAttribute === 'slider' ||
                item.tagAttribute === 'rate'
              ) {
                // data中的val都是string类型
                returnData[item.id.split('_')[0]] =
                  typeof val === 'string' ? JSON.parse(val) : val
              } else if (
                item.tagAttribute === 'user-selector' ||
                item.tagAttribute === 'org-selector'
              ) {
                // 选人选组件应为对象
                returnData[item.id.split('_')[0]] =
                  typeof val === 'string' ? JSON.parse(val) : val
              } else if (item.tagAttribute === 'information') {
                let newVal = typeof val === 'string' ? JSON.parse(val) : val
                if (newVal) {
                  returnData[item.id.split('_')[0]] = {
                    userFullname: newVal.userFullname || '',
                    prjDepName: newVal.prjDepName || '',
                    userTelephoneNum: newVal.userTelephoneNum || '',
                    createDate: newVal.createDate || ''
                  }
                } else {
                  returnData[item.id.split('_')[0]] = {
                    userFullname: '',
                    prjDepName: '',
                    userTelephoneNum: '',
                    createDate: ''
                  }
                }
              } else if (item.tagAttribute === 'switch2') {
                // 开关组件
                returnData[item.id.split('_')[0]] = val === 'true'
              } else if (item.tagAttribute === 'upload') {
                // 上传组件
                // let valArr = val.indexOf(',') > -1 ? JSON.parse(val) : val
                returnData[item.id.split('_')[0]] = JSON.parse(val)[0]
              } else {
                returnData[item.id.split('_')[0]] = val
              }
            })

            // 保留的字段
            let idArr = this.field.map((item) => item.id)
            idArr.push(
              'create_by_full_name',
              'create_date',
              'id',
              'update_by_full_name',
              'serial_number'
            )
            // 最后的值
            this.dataValues = {}
            idArr.forEach((item) => {
              if (item.includes('_asc')) {
                this.dataValues[item] = returnData[item.split('_asc')[0]] || ''
              } else {
                this.dataValues[item] = returnData[item] || ''
              }
            })
            //  this.$message({
            //     showClose: true,
            //     message: this.LANG.SORT_SUCCESS,
            //     type: 'success'
            // })
          }
        })
        .catch(() => {
          this.$message({
            showClose: true,
            message: '表单信息加载失败',
            type: 'error'
          })
        })
    },
    // id this,checkedForm
    async saveForm() {
      await this.getValue()
      let form = {
        id: this.checkedForm,
        ...this.dataValues
      }
      this.$emit('associationFormChange', [form])
      this.formListVisible = false
      this.detailVisible = true
    }
  }
}
</script>
<style scoped lang="scss">
.form {
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 20px;
  // &:hover {
  //     border-color: steelblue;
  // }
}
.title {
  width: 100%;
  line-height: 36px;
}
.content {
  width: 100%;
  height: 36px;
}
.dialog-content {
  width: 100%;
  padding: 10px;
}
.checked-form-content {
  width: 100%;
  padding: 10px;
}
.form-content {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 8px;
  .time {
    width: 114px;
    text-align: right;
  }
  .form-detail {
    display: flex;
    .name {
      // text-align-last:justify;
      // justify-content: space-between;
      // width: 100px;
      padding-right: 10px;
    }
  }
}

::v-deep .fks-form-item .fks-form-item {
  margin-bottom: 10px;
}
</style>
